<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");

// 读取 JSON 输入
$input = json_decode(file_get_contents("php://input"), true);

// 检查是否传入 messages
if (!isset($input["messages"]) || !is_array($input["messages"])) {
    echo json_encode(["error" => "messages 参数缺失"]);
    exit;
}

$messages = $input["messages"];  // 多轮历史对话

$apiKey = "a7c7e74a48a44a3a9880123144140add.bJcXDHZx8YK9XKo2";

$payload = [
    "model" => "glm-4-flash",
    "messages" => $messages,
    "max_tokens" => 1024,
    "temperature" => 0.7
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => "https://open.bigmodel.cn/api/paas/v4/chat/completions",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
        "Authorization: Bearer ".$apiKey
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_SSL_VERIFYPEER => false
]);

$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($response === false) {
    echo json_encode(["error" => "curl错误: ".$error]);
    exit;
}

// 直接返回 API 原始响应
echo $response;
?>
